package cn.edu.seu.herald.informationplatform.dao.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.edu.seu.herald.informationplatform.bean.auth.UserSession;

public class UserSessionDao extends DataAccessObject{
	private static UserSessionDao daoInstance=null;	
	//Constructor of userDao
	protected UserSessionDao(){	
	}
	//Get userDao instance
	public static UserSessionDao getDao(){
		if(daoInstance==null){
			daoInstance=new UserSessionDao();
		}
		return daoInstance;
	}
	
	public boolean contains(int id) throws SQLException {
		Connection con = getConnectionLeague();
		try {
			PreparedStatement ps = con.prepareStatement("select * from lg_user_session where id=?");
			ps.setInt(1,id);
			int count = 0;
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				count++;
			}
			closeRs(rs);
			if (count==0) {
				return false;
			}else {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	//getl
	public UserSession getUserSessionById(int id)throws SQLException{
		Connection con = getConnectionLeague();
		UserSession us = new UserSession();
		try {
			PreparedStatement ps = con.prepareStatement("select * from lg_user_session where id=?");
			ps.setInt(1,id);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				us.setUserId(rs.getInt(2));
				us.setExpireTime(rs.getLong(3));
				us.setIpAddress(rs.getString(4));
			}
			return us;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		finally{
			closeCon(con);
		}
	}
	
	public void deleteUserSession(int id)throws SQLException{
		Connection con = getConnectionLeague();
		try {
			PreparedStatement ps = con.prepareStatement(
					"delete from lg_user_session where id=?");
			ps.setInt(1, id);
			ps.executeUpdate();
		} finally {
			con.close();
		}
	}
	
}